package com.yjd.api.callback;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.encrypt.AesUtil;
import com.yjd.comm.fundservice.dto.QKLoanNoticeModel;
import com.yjd.comm.fundservice.dto.QkCallBackMsgDto;
import com.yjd.comm.fundservice.service.ICallbackService;
import com.yjd.comm.fundservice.util.QianKangServerUtil;
import com.yjd.comm.repayment.service.IRepaymentDataService;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.StringUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * 第三方资金服务相关操作
 * Created by yangchangyan on 2018/1/26.
 */
@Controller
@Scope("prototype")
public class CallbackControl extends BaseControl {

    @Resource
    private ICallbackService callbackService;

    @Resource
    private IRepaymentDataService repaymentDataService;

    /**
     * 贷款通知回调
     */
    @RequestMapping(value = "/loan/callback")
    @ResponseBody
    public String loanCallback() throws Exception {
        try {
            String msg = ServletUtil.getJsonRequest(request);
            Assert.hasLength(msg, "信息为空");
            logger.info("接到回调信息："+msg);
            QkCallBackMsgDto callBackMsgDto = StringUtil.getObject(msg,QkCallBackMsgDto.class);
            if(StringUtil.isEmpty(callBackMsgDto.getData())){
                FrameUtil.throwBaseException1("请求data参数不能为空");
            }

            if(StringUtil.isEmpty(callBackMsgDto.getIv())){
                FrameUtil.throwBaseException1("请求iv参数不能为空");
            }

            if(StringUtil.isEmpty(callBackMsgDto.getSc())){
                FrameUtil.throwBaseException1("请求sc参数不能为空");
            }

            String key = QianKangServerUtil.getKeyPlainText(callBackMsgDto.getSc());
            // 贷款通知信息
            QKLoanNoticeModel loanApplyNotice = QianKangServerUtil.parseCallbackResponse(key,"/loan/callback", callBackMsgDto, QKLoanNoticeModel.class);
            Assert.notNull(loanApplyNotice, "解析消息失败");
            callbackService.callbackProcess(loanApplyNotice);
            return AesUtil.encryptByCBC(JSON.toJSONString(FrameUtil.newHashMap("code",0)),key,callBackMsgDto.getIv());
        }catch (Exception e){
            logger.error("资金方回调处理异常,错误信息:"+e);
        }
       return JSON.toJSONString(FrameUtil.newHashMap("code",1));
    }

}
